<template>
  <div class="category-container">
    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-state">
      <el-empty :description="errorMessage" :image-size="200">
        <template #image>
          <el-icon color="#F56C6C" :size="60">
            <Warning />
          </el-icon>
        </template>
      </el-empty>
    </div>

    <!-- 当前分类标题 -->
    <div class="current-category" v-if="currentCategory && !errorMessage">
      <h3 class="section-title">{{ currentCategory.name }}</h3>
    </div>

    <!-- 商家列表 -->
    <div class="business-section" v-if="!errorMessage">
      <div v-if="businessList.length > 0" class="business-list">
        <el-card
            v-for="business in businessList"
            :key="business.businessId"
            class="business-card"
            shadow="hover"
            @click="goToBusiness(business.businessId)"
        >
          <div class="business-content">
            <div class="business-image">
              <img :src="business.head" alt="商家图片" class="business-img">
            </div>
            <div class="business-info">
              <h4 class="business-name">{{ business.businessName }}</h4>
              <p class="business-address">
                <el-icon><Location /></el-icon>
                {{ business.address }}
              </p>
              <div class="business-rating">
                <el-rate
                    v-model="business.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}分"
                    :max="5"
                />
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div v-else class="empty-state">
        <el-empty description="该分类暂无商家" />
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {Location, Warning} from '@element-plus/icons-vue'

const router = useRouter()
const errorMessage = ref('')
const businessList = ref([])
const currentCategory = ref(null)

// 商家分类数据 (与home.vue保持一致)
const allCategories = [
  {type: 1, name: '汉堡炸鸡', image: '/src/static/image/type/hamburger.png'},
  {type: 2, name: '奶茶饮料', image: '/src/static/image/type/bubble_tea.png'},
  {type: 3, name: '龙虾烧烤', image: '/src/static/image/type/barbecue.png'},
  {type: 4, name: '快餐便当', image: '/src/static/image/type/fast_food.png'},
  {type: 5, name: '日韩料理', image: '/src/static/image/type/sushi.png'},
  {type: 6, name: '火锅串串', image: '/src/static/image/type/hot_pot.png'},
  {type: 7, name: '披萨意面', image: '/src/static/image/type/pizza.png'},
  {type: 8, name: '甜品小吃', image: '/src/static/image/type/dessert.png'}
]

// 跳转到商家详情
const goToBusiness = (businessId) => {
  localStorage.setItem('business_id', businessId)
  router.push('/business')
}

// 获取当前分类的商家列表
const fetchBusinessByType = async () => {
  try {
    const type = localStorage.getItem('business_type')
    if (!type) {
      errorMessage.value = '未获取到分类信息'
      return
    }

    // 设置当前分类信息
    currentCategory.value = allCategories.find(cat => cat.type === parseInt(type))
    if (!currentCategory.value) {
      errorMessage.value = '分类信息不存在'
      return
    }

    const token = localStorage.getItem('access_token')
    if (!token) {
      errorMessage.value = '请先登录以获取商家信息'
      return
    }

    const response = await fetch(`http://localhost:8080/business/type/${type}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      const errorData = await response.json()
      handleApiError(response.status, errorData)
      return
    }

    businessList.value = await response.json()

  } catch (error) {
    console.error('Error fetching business list:', error)
    errorMessage.value = '服务器连接错误，请检查您的连接或稍后重试'
  }
}

// 处理API错误
const handleApiError = (status, errorData) => {
  switch (status) {
    case 401:
      errorMessage.value = '登录已过期，请重新登录'
      break
    case 403:
      errorMessage.value = '访问被拒绝，您可能没有权限'
      break
    case 503:
      errorMessage.value = '服务暂时不可用，请稍后重试'
      break
    default:
      errorMessage.value = errorData?.message || '服务器繁忙，请稍后重试'
      break
  }
}

// 在组件挂载时获取business列表
onMounted(() => {
  fetchBusinessByType()
})
</script>

<style scoped>
.category-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 12px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 错误提示 */
.error-state {
  padding: 40px 0;
  text-align: center;
  background-color: white;
  border-radius: 12px;
  margin-bottom: 20px;
}

/* 当前分类 */
.current-category {
  margin-bottom: 20px;
  text-align: center;
}

.category-header-img {
  width: 100%;
  max-height: 150px;
  object-fit: cover;
  border-radius: 12px;
  margin-top: 10px;
}

/* 区块标题 */
.section-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 15px 8px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  display: inline-block;
  width: 3px;
  height: 14px;
  background: #409eff;
  border-radius: 2px;
  margin-right: 8px;
}

/* 商家列表 */
.business-section {
  margin-bottom: 20px;
}

.business-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.business-card {
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
}

.business-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.business-content {
  display: flex;
  padding: 15px;
  gap: 15px;
}

.business-image {
  width: 90px;
  height: 90px;
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
}

.business-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.business-card:hover .business-img {
  transform: scale(1.05);
}

.business-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-width: 0;
}

.business-name {
  margin: 0 0 6px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.business-address {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 4px;
}

.business-address .el-icon {
  font-size: 14px;
  color: #999;
}

.business-rating {
  display: flex;
  align-items: center;
}

/* 空状态 */
.empty-state {
  padding: 40px 0;
  text-align: center;
  background-color: white;
  border-radius: 12px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .business-content {
    padding: 12px;
    gap: 12px;
  }

  .business-image {
    width: 80px;
    height: 80px;
  }

  .business-name {
    font-size: 15px;
  }

  .business-address {
    font-size: 12px;
  }
}

@media (min-width: 600px) {
  .business-card {
    border-radius: 16px;
  }

  .business-image {
    width: 100px;
    height: 100px;
  }

  .business-name {
    font-size: 17px;
  }

  .business-address {
    font-size: 14px;
  }
}
</style>